#include "mq_connection.hpp"
#include "../mqcommon/mq_logger.hpp"
#include <jsoncpp/json/json.h>

void cb(const mq::Channel::ptr &channel,const std::string&consumer_tag,mq::BasicProperties *bp ,const std::string &body)
{
    Json::Value root;
    Json::Reader reader;
    reader.parse(body,root);
    std::string id = root["id"].asString();
    std::string name = root["name"].asString();
    DLOG("%s 消费了消息：%s",consumer_tag.c_str(),name.c_str());
    channel->basicAck(bp->id());
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        std::cout << "usage: ./consume_client queue1\n";
        return -1;
    }
    //1.定义异步工作线程
    mq::AsyncWorker::ptr worker = std::make_shared<mq::AsyncWorker>();
    //2.创建连接
    mq::Connection::ptr conn = std::make_shared<mq::Connection>("127.0.0.1",8888,worker);
    //3.创建信道
    mq::Channel::ptr channel = conn->openChannel();
    //4. 通过信道提供的服务完成所需
        //1.创建一个交换机
    google::protobuf::Map<std::string, std::string> args;
    channel->declareExchange("exchange1",mq::ExchangeType::FANOUT,true,false,args);
        //2.创建队列1
    channel->declareQueue("queue1",false,true,false,args);
        //3.创建队列2
    // channel->declareQueue("queue2",false,true,false,args);
        //4.绑定队列
    channel->queueBind("exchange1","queue1","queue1");
    // channel->queueBind("exchange1","queue2","news.music.#");
    
    auto Functor = std::bind(cb,channel,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3);

    //订阅队列1
    channel->basicConsume("consume1",argv[1],false,Functor);

    while(1) std::this_thread::sleep_for(std::chrono::seconds(3));
    
    conn->closeChannel(channel);
    return 0;
}